<template>
  <div class="tables-wrapper">
    <div class="flex justify-between items-center" style="margin: px">
      <el-button type="info" @click="craetePartInfo">创建备件库信息</el-button>
      <el-button type="success" @click="updatePartInfo"
        >增加或减少零件</el-button
      >
    </div>
    <div class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="getHeaderCellStyle"
        :cell-style="getRowCellStyle"
      >
        <el-table-column prop="createTime" label="时间" width="105" />
        <el-table-column prop="personInCharge" label="检修负责人" width="95" />
        <el-table-column prop="customerName2" label="客户" width="70" />
        <el-table-column prop="content" label="操作描述" />
      </el-table>
    </div>
    <div class="table-container">
      <el-table
        :data="formattedPartData"
        style="width: 100%"
        :header-cell-style="getHeaderCellStyle"
        :cell-style="getRowCellStyle"
      >
        <el-table-column prop="partNumber" label="编号" width="146" />
        <el-table-column prop="partName" label="零件名称" width="146" />
        <el-table-column prop="sku" label="数量" />
      </el-table>
    </div>
    <!-- 弹窗 -->
    <el-dialog title="创建零件信息" v-model="dialogVisibleCreate" width="30%">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="客户名">
          <el-input v-model="customerName"></el-input>
        </el-form-item>
        <el-form-item label="零件编号">
          <el-input v-model="partNum"></el-input>
        </el-form-item>
        <el-form-item label="零件名称">
          <el-input v-model="partName"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="partCount"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleCreate = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="增加零件数量" v-model="dialogVisibleUpdate" width="30%">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="客户名">
          <el-input v-model="customerName"></el-input>
        </el-form-item>
        <el-form-item label="零件编号">
          <el-input v-model="partNum"></el-input>
        </el-form-item>
        <el-form-item label="零件名称">
          <el-input v-model="partName"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="partCount" placeholder="输入-999则删除这个零件信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleUpdate = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, watch } from "vue";
import {
  ElButton,
  ElDialog,
  ElFormItem,
  ElInput,
  ElMessageBox,
  ElMessage,
} from "element-plus";

import { createPartsInApi,updatePartsInApi } from "../api/packaging.js";
const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
  partData: {
    type: Array,
    required: true,
  },
  customerNameData: {
    type: Array,
    required: true,
  }
});
const tableData = ref([]);
const formattedPartData = ref([]);
const customerName = ref("");

watch(
  () => props.data,
  (newVal) => {
    if (Array.isArray(newVal)) {
      const formattedData = newVal.map((item) => ({
        createTime: new Date(item.CreatedAt).toLocaleString(),
        personInCharge: item.personInCharge,
        content: item.content,
        customerName2:item.customerName,
      }));
      tableData.value = formattedData;
    } else {
      console.error("传递给子组件的数据不是数组:", newVal);
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.partData,
  (newVal) => {
    if (Array.isArray(newVal)) {
      const formatted = newVal.map((item) => ({
        partNumber: item.partNumber,
        partName: item.partName,
        sku: item.sku,
      }));
      formattedPartData.value = formatted;
    } else {
      console.error("传递给子组件的 partData 不是数组:", newVal);
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.customerNameData,
  (newVal) => {
    customerName.value=newVal;
    console.log("customerName:",customerName.value)
  },
  { deep: true, immediate: true }
);

function getHeaderCellStyle() {
  return {
    background: "#182434", // 设置表头背景颜色
    color: "fff", // 可以设置文本颜色，使用 Element Plus 的 CSS 变量
    "text-align": "left", // 居中对齐
    border: "none",
  };
}

function getRowCellStyle({ row, rowIndex }) {
  return {
    background: rowIndex % 2 === 0 ? "#f5f5f7" : "#ffffez",
    color: "#1d1d1f",
  };
}
const dialogVisibleCreate = ref(false);
const dialogVisibleUpdate = ref(false);
function craetePartInfo() {
  dialogVisibleCreate.value = true;
}
function updatePartInfo() {
  dialogVisibleUpdate.value = true;
}

const partNum = ref("");
const partName = ref("");
const partCount = ref("");
// 确认按钮处理
const confirm = () => {
  let content = "";
  // 构建显示内容
  if (dialogVisibleCreate.value === true) {
    content = `客户: ${customerName.value}<br/>零件编号: ${partNum.value}<br/>零件名称: ${partName.value}<br/>数量：${partCount.value}`;
  } else if (dialogVisibleUpdate.value === true) {
    content = `客户: ${customerName.value}<br/>零件编号: ${partNum.value}<br/>零件名称: ${partName.value}<br/>数量：${partCount.value}`;
  }

  ElMessageBox({
    title: "确认",
    message: `请确认以下信息:<br/>${content}`,
    dangerouslyUseHTMLString: true, // 允许 message 中的 HTML
    confirmButtonText: "确定",
    cancelButtonText: "修改",
    type: "warning",
    showConfirmButton: true,
    showCancelButton: true,
  })
    .then(() => {
      if (dialogVisibleCreate.value === true) {
        submit();
      } else if (dialogVisibleUpdate.value === true) {
        submitUpdate();
      }
    })
    .catch(() => {
      console.log("用户点击取消按钮");
    });
};
const submit = async () => {
  // 获取输入值
  const partNumValue = partNum.value;
  const partNameValue = partName.value;
  const partCountValue = Number(partCount.value);
  const partCustomerValue = customerName.value;
  // 校验输入是否为空
  if (!partNameValue || !partCountValue) {
    ElMessage.error("请输入所有必填项");
    return;
  }

  // 校验输入是否为数字
  if (isNaN(partCountValue)) {
    ElMessage.error("数量必须为数字");
    return;
  }
  try {
    const response = await createPartsInApi(
      partNumValue,
      partNameValue,
      partCountValue,
      partCustomerValue
    );

    if (response && response.data && response.status === 200) {
      ElMessage.success("添加成功: " + response.data.message);
    } else {
      ElMessage.error("提交失败: " + (response?.data?.error || "操作未成功"));
    }
  } catch (error) {
    console.error("请求失败:", error);

    if (error.response) {
      // 后端返回的错误信息
      ElMessage.error("请求失败: " + error.response.data.message);
    } else if (error.message) {
      // 请求错误，但非后端返回，如网络错误
      ElMessage.error("请求失败: " + error.message);
    } else {
      // 其他错误
      ElMessage.error("请求失败");
    }
  }

  dialogVisibleCreate.value = false;
};

const submitUpdate = async () => {
  // 获取输入值
  const partNumValue = partNum.value;
  const partNameValue = partName.value;
  const partCountValue = Number(partCount.value);
  const customer = ref(localStorage.getItem("customer") || "");
  const partCustomerValue = customerName.value;
  // 校验输入是否为空
  if (!partNameValue || !partCountValue) {
    ElMessage.error("请输入所有必填项");
    return;
  }

  // 校验输入是否为数字
  if (isNaN(partCountValue)) {
    ElMessage.error("数量必须为数字");
    return;
  }
  try {
    const response = await updatePartsInApi(
      partNumValue,
      partNameValue,
      partCountValue,
      customer.value,
      partCustomerValue
    );

    if (response && response.data && response.status === 200) {
      ElMessage.success("添加成功: " + response.data.message);
    } else {
      ElMessage.error("提交失败: " + (response?.data?.error || "操作未成功"));
    }
  } catch (error) {
    console.error("请求失败:", error);

    if (error.response) {
      // 后端返回的错误信息
      ElMessage.error("请求失败: " + error.response.data.message);
    } else if (error.message) {
      // 请求错误，但非后端返回，如网络错误
      ElMessage.error("请求失败: " + error.message);
    } else {
      // 其他错误
      ElMessage.error("请求失败");
    }
  }

  dialogVisibleUpdate.value = false;
};
</script>
  
  <style scoped>
.tables-wrapper {
  display: flex;
  flex-direction: column;
  gap: 10px;
  /* 可选：增加间距 */
}

.table-container {
  max-height: 235px; /* 设置最大高度 */
  overflow-x: auto;
  overflow-y: auto; /* 添加垂直滚动 */
  display: block; /* 显式声明 */
}

.el-table th,
.el-table td {
  padding: 4px; /* 调整内边距 */
  font-size: 14px; /* 调整字体大小 */
}

/* 媒体查询，针对不同屏幕尺寸调整样式 */
@media (max-width: 480px) {
  .el-table th,
  .el-table td {
    padding: 2px;
    font-size: 12px;
  }
}
</style>